package com.weareint.common.dto;

import com.weareint.common.exceptions.SystemRuntimeException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Objects;

/**
 *
 *
 * <pre>
 *      所有可支持的类型
 * </pre>
 *
 * @author wangg
 * @date 2021/7/1010:51
 */
public class Types {

    /**
     *
     *
     * <pre>
     *     依据 type 获取可用的Enum
     * </pre>
     *
     * @param type 前台传入的类型
     * @return {@link Type}
     */
    public static Type getTypeEnum(String type) {
        if (null == type) {
            return null;
        }
        type = type.toLowerCase();
        Type[] values = Type.values();
        for (Type value : values) {
            if (Objects.equals(value.type.toLowerCase(), type)) {
                return value;
            }
        }
        return null;
    }

    /** 转型 */
    public enum Type {
        /** 字符串转型 */
        STRING("string") {
            @Override
            public Object cast(String val) {
                if (null == val || val.trim().length() == 0) {
                    throw new SystemRuntimeException("val is null or empty");
                }
                return val.trim();
            }
        },
        /** 整数转型 */
        INT("integer") {
            @Override
            public Object cast(String val) {
                try {
                    return Integer.parseInt(val);
                } catch (Exception e) {
                    throw new SystemRuntimeException("Not cast " + val + " to Integer");
                }
            }
        },
        LONG("long") {
            @Override
            public Object cast(String val) {
                try {
                    return Long.parseLong(val);
                } catch (Exception e) {
                    throw new SystemRuntimeException("Not cast " + val + " to Long");
                }
            }
        },
        /** 浮点数转型 */
        DOUBLE("double") {
            @Override
            public Object cast(String val) {
                try {
                    return Double.parseDouble(val);
                } catch (Exception e) {
                    throw new SystemRuntimeException("Not cast " + val + " to Double");
                }
            }
        },
        /** 日期转型 */
        DATE("date") {
            @Override
            public Object cast(String val) {
                try {
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(val);
                } catch (ParseException e) {
                    throw new SystemRuntimeException(
                            "Not cast " + val + " to Date, format=yyyy-MM-dd HH:mm:ss");
                }
            }
        };

        private final String type;

        Type(String type) {
            this.type = type;
        }

        public abstract Object cast(String val);
    }
}
